package com.jinbo.footmessageworker.person;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jinbo.footmessageworker.BaseActivity;
import com.jinbo.footmessageworker.MyApplication;
import com.jinbo.footmessageworker.R;
import com.jinbo.footmessageworker.httpbean.WorkerInformationBean;
import com.jinbo.footmessageworker.httpretrofit.BusinessController;
import com.jinbo.footmessageworker.httpretrofit.HttpProtocolFactory;
import com.jinbo.footmessageworker.httpretrofit.Listener;
import com.jinbo.footmessageworker.utils.CropImageUtils;
import com.jinbo.footmessageworker.utils.DialogUtils;
import com.jinbo.footmessageworker.utils.LocalPreferencesHelper;
import com.jinbo.footmessageworker.view.TitleBarView;

import java.io.File;

/**
 *
 */
public class PersonInfoActivity extends BaseActivity implements View.OnClickListener {

    //请求码
    private static final int REQUEST_IMAGE = 100;
    private static final int REQUEST_CROP = 101;
    private static final int REQUEST_TAKE_PICTURE = 102;

    public static final File temp= new File(MyApplication.app.getTmpDir(),"temp1.jpg");
    public static final File des= new File(MyApplication.app.getTmpDir(),"head1.jpg");//头像路径要改下
    public static final Uri imageUri=Uri.fromFile(temp);
    public static final Uri desUri=Uri.fromFile(des);


    public static final int MODIFY_NICK_NAME = 103;
    public static final int MODIFY_SPECIALITY= 105;
    public static final int MODIFY_EMAIL = 108;
    public static final int MODIFY_PHONE= 109;



    private ImageView img_head_view;
    private TextView tv_name, tv_sex, tv_phone, tv_email,tv_nick_name,tv_age,tv_speciality;

    private RadioButton rb_male, rb_female;
    View parent;
    DialogUtils dialogUtils;
    Dialog dialog_sex;
   // private String mSex;

   // Boolean isUpdateName=false;
   // Boolean isUpdateHead=false;
    public static void launch(Activity activity,int requestCode) {
        Intent intent = new Intent(activity, PersonInfoActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_back_layout:
                finish();
                break;
        }
    }

    @Override
    public void finish() {

      //  Intent intent = new Intent();
        ///if(isUpdateName)
        //    intent.putExtra("name", tv_name.getText().toString());
       // if(isUpdateHead)
       //     intent.putExtra("head", des.getAbsolutePath());
        // 设置结果，并进行传送
        setResult(RESULT_OK);
        super.finish();


    }
    String user_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        //int i = (int) (Math.random() * 1000000 + 100000);
        user_id=MyApplication.local.getString(LocalPreferencesHelper.USER_ID);
        //des= new File(MyApplication.app.getTmpDir(),user_id+"head.jpg");
        initTitleBarView();
        initViews();
        initData();

    }
    public void initTitleBarView() {
        TitleBarView titleBarView = (TitleBarView) findViewById(R.id.tbv_person_info);
        titleBarView.setCenterTitle("个人信息");
        titleBarView.setLeftBackButtonIsVisibler(true);
        titleBarView.setListener(TitleBarView.TitleBarEnum.ll_leftBackImageLayout, this);
    }

    private void initViews() {

        img_head_view = (ImageView) findViewById(R.id.img_head_view);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_email = (TextView) findViewById(R.id.tv_email);
        tv_nick_name = (TextView) findViewById(R.id.tv_nick_name);
        tv_age= (TextView) findViewById(R.id.tv_age);
        tv_speciality= (TextView) findViewById(R.id.tv_speciality);
        parent= LayoutInflater.from(this).inflate(R.layout.dialog_content_radiogroup, null);
        rb_male = (RadioButton) parent.findViewById(R.id.rb_male);
        rb_female = (RadioButton) parent.findViewById(R.id.rb_female);
        dialogUtils= new DialogUtils(this,0,null, true);
        dialogUtils.setTitle("性别");
        dialogUtils.setView(parent);
        dialogUtils.setButtons(null,null,null);
        dialog_sex=dialogUtils.create();

    }

    private void initData()
    {
        String userHead=MyApplication.local.getString(user_id+LocalPreferencesHelper.USER_HEAD_URL);
        String phone=MyApplication.local.getString(user_id+LocalPreferencesHelper.USER_MOBILE);
        String mail=MyApplication.local.getString(user_id+LocalPreferencesHelper.USER_MAIl);
        String userName= MyApplication.local.getString( user_id+ LocalPreferencesHelper.USER_NAME);
        String userNickName = MyApplication.local.getString(user_id + LocalPreferencesHelper.USER_NICKNAME);
        String  userAge = MyApplication.local.getString(user_id+ LocalPreferencesHelper.USER_AGE);
        String userSpeciality =MyApplication.local.getString(user_id + LocalPreferencesHelper.USER_SPECIALITY);



        String mSex=MyApplication.local.getString(user_id+LocalPreferencesHelper.USER_SEX);
        if(!userName.equals(""))
        {
            tv_name.setText(userName);
        }
        if(!userHead.equals(""))
        {
           // Uri imageUri=Uri.fromFile(new File(headPath));
            //img_head_view.setImageURI(imageUri);
            String userHeadUrl = HttpProtocolFactory.HOST_URL_USER + userHead;
            Glide.with(this)
                    .load(userHeadUrl)
                  //  .crossFade()
                   .placeholder(R.drawable.head_small)
                    .into(img_head_view);
            //Glide.clear(img_head_view);

        }
        if(!phone.equals(""))
        {
            tv_phone.setText(phone);
        }
        if(!mail.equals(""))
        {
            tv_email.setText(mail);
        }
        if(!mSex.equals(""))
        {
            tv_sex.setText(mSex);
        }
        if(!userNickName.equals(""))
        {
            tv_nick_name.setText(userNickName);
        }

        if(!userAge.equals(""))
        {
            tv_age.setText(userAge);
        }
        if(!userSpeciality.equals(""))
        {
            tv_speciality.setText(userSpeciality);
        }

    }



    //修改头像
    public void modifyHeadView(View view) {
        //isUpdateHead=true;
        DialogUtils dialogUntils = new DialogUtils(PersonInfoActivity.this,
                "center", true,1);
        dialogUntils.setButtons(null, "取消",
                new DialogUtils.OnDialogButtonClickListener() {
                    @Override
                    public void onDialogButtonClick(Context context, DialogUtils builder, Dialog dialog, int dialogId, int which) {
                        if (which == DialogUtils.OnDialogButtonClickListener.BUTTON_RIGHT) {
                            // ActivitiesHelper.getInstance().closeAll();
                            // LoginActivity.launch(FindPasswordActivity.this);
                        }
                    }
                });
        dialogUntils.setItems(R.array.sign, new DialogUtils.OnDialogItemClickListener() {

            @Override
            public void OnDialogItemClick(Context context,
                                          DialogUtils builder, Dialog dialog, int position) {
                if (position == 0) {
                    //CropWrapper.camera(BaseApplication.app.getCropTmpDir(), PersonInfoActivity.this);
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, REQUEST_TAKE_PICTURE);
                } else {

                    Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent,REQUEST_IMAGE);
                }

            }

        });
        Dialog dialog=dialogUntils.create();//.show();

        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int)(display.getWidth()); //设置宽度
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setAttributes(lp);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }

    //修改用户名
    public void modifyNickName(View view) {
        PersonInfoUpdateTextActivity.launch(this, MODIFY_NICK_NAME, tv_nick_name.getText().toString(), 0);
    }

    //修改性别

    /**
     *
     * @param view
     */
    public void modifySex(View view) {
       String  sex=MyApplication.local.getString(user_id+LocalPreferencesHelper.USER_SEX);
        if (sex.equals("男")) {
            rb_male.setChecked(true);
            rb_female.setChecked(false);
        } else {
            rb_male.setChecked(false);
            rb_female.setChecked(true);
        }

        dialog_sex.show();
    }

    //修改邮箱
    public void modifyEmail(View view) {
        PersonInfoUpdateTextActivity.launch(this, MODIFY_EMAIL, tv_email.getText().toString(), 1);
    }
    //修改电话
    public void modifyPhone(View view) {
        PersonInfoUpdateTextActivity.launch(this, MODIFY_PHONE, tv_phone.getText().toString(),2);
    }
    //修改特长
    public void modifySpeciality(View view) {
        PersonInfoUpdateTextActivity.launch(this, MODIFY_SPECIALITY, tv_speciality.getText().toString(),3);
    }
    int mSelectNumber;
    //修改年龄
    public void modifyAge(View view) {
        mSelectNumber=Integer.valueOf(MyApplication.local.getString(user_id + LocalPreferencesHelper.USER_AGE));
        View parent= LayoutInflater.from(this).inflate(R.layout.dialog_picker_age_view, null);
        NumberPicker np=(NumberPicker)parent.findViewById(R.id.number_picker);
        np.setMinValue(10);
        np.setMaxValue(80);
        np.setValue(mSelectNumber);
        np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                mSelectNumber=newVal;
            }
        });
        DialogUtils dialogUtils= new DialogUtils(this,0,null,false);
        dialogUtils.setView(parent);
        dialogUtils.setButtons("取消", "确定",
                new DialogUtils.OnDialogButtonClickListener() {
                    @Override
                    public void onDialogButtonClick(Context context, DialogUtils builder, Dialog dialog, int dialogId, int which) {
                        if (which == DialogUtils.OnDialogButtonClickListener.BUTTON_RIGHT) {
                            BusinessController.getInstance().modifyUserInformation(user_id,String.valueOf(mSelectNumber),4, new Listener<WorkerInformationBean>() {

                                @Override
                                public void onStart(Object... params) {
                                    showProgressDialog("请稍后...");
                                }

                                @Override
                                public void onComplete(WorkerInformationBean result, Object... params) {
                                    dismissProgressDialog();
                                    show("修改年龄成功");
                                    MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_AGE,String.valueOf(mSelectNumber) );
                                    // tv_name.setText(name);
                                    tv_age.setText(String.valueOf(mSelectNumber));
                                }

                                @Override
                                public void onFail(final String msg, Object... params) {
                                    dismissProgressDialog();
                                    if (TextUtils.isEmpty(msg)) {
                                    } else {
                                        show(msg);
                                    }
                                }
                            });

                        }
                    }
                });
        dialogUtils.create().show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PICTURE) {
                CropImageUtils.cropImageUri(this,imageUri,desUri,180,180,REQUEST_CROP);
            }
            if (requestCode == REQUEST_IMAGE) {
                //mProgressDialog.show();
        /*        Cursor cursor = getContentResolver().query(
                        data.getData(), null, null, null, null);
                cursor.moveToFirst();
                final String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
                //BitmapFactory.Options opts = new BitmapFactory.Options();
               // opts.inSampleSize = 4;
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);//,opts);*/
                CropImageUtils.cropImageUri(this,data.getData(),desUri,180,180,REQUEST_CROP);

                // bitmap.setPixel(3120,4208,0);
                //  mCircleImage.setImageBitmap(bitmap);


            }
            if (requestCode == REQUEST_CROP) {


                BusinessController.getInstance().modifyFace(user_id,desUri.getPath(),1, new Listener<WorkerInformationBean>() {

                    @Override
                    public void onStart(Object... params) {
                        showProgressDialog("请稍后...");
                    }

                    @Override
                    public void onComplete(WorkerInformationBean result, Object... params) {
                        dismissProgressDialog();
                        show("上传头像成功");
                       // isUpdateHead=true;
                        //MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.USER_HEAD_PATH, des.getAbsolutePath());
                        //DialogUtils.(result.head);
                       // new DialogUtils(PersonInfoActivity.this, "center", true, 0).setMessage(result.head).setButtons(null, "确定", null).create().show();
                        MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_HEAD_URL, result.head);
                       // MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_NAME, "FDASFADSFADSF");
                        //MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.USER_HEAD_CODE,result.random_code);
                        Bitmap bitmap=CropImageUtils.decodeUriAsBitmap(PersonInfoActivity.this,desUri);
                        img_head_view.setImageBitmap(bitmap);
                      //  if(temp.exists())
                      //      temp.delete();
                      // if(des.exists())
                       //     des.delete();

                    }

                    @Override
                    public void onFail(final String msg, Object... params) {
                        dismissProgressDialog();
                        if (TextUtils.isEmpty(msg)) {
                        } else {
                            show(msg);
                        }
                    }
                });
            }
            if (requestCode ==MODIFY_NICK_NAME) {
                final String name = data.getStringExtra("text");

                //isUpdateName=true;

                BusinessController.getInstance().modifyUserInformation(user_id, name, 0, new Listener<WorkerInformationBean>() {

                    @Override
                    public void onStart(Object... params) {
                        showProgressDialog("请稍后...");
                    }

                    @Override
                    public void onComplete(WorkerInformationBean result, Object... params) {
                        dismissProgressDialog();
                        show("修改昵称成功");
                        MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_NICKNAME, name);
                        tv_nick_name.setText(name);
                    }

                    @Override
                    public void onFail(final String msg, Object... params) {
                        dismissProgressDialog();
                        if (TextUtils.isEmpty(msg)) {
                        } else {
                            show(msg);
                        }
                    }
                });
            }
            if (requestCode ==MODIFY_EMAIL) {
                final String email = data.getStringExtra("text");
                BusinessController.getInstance().modifyUserInformation(user_id, email,1, new Listener<WorkerInformationBean>() {

                    @Override
                    public void onStart(Object... params) {
                        showProgressDialog("请稍后...");
                    }

                    @Override
                    public void onComplete(WorkerInformationBean result, Object... params) {
                        dismissProgressDialog();
                        show("修改用户邮箱成功");
                        MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_MAIl, email);
                       // tv_name.setText(name);
                        tv_email.setText(email);
                    }

                    @Override
                    public void onFail(final String msg, Object... params) {
                        dismissProgressDialog();
                        if (TextUtils.isEmpty(msg)) {
                        } else {
                            show(msg);
                        }
                    }
                });

            }
            if (requestCode ==MODIFY_PHONE) {
                final String str = data.getStringExtra("text");
                BusinessController.getInstance().modifyUserInformation(user_id, str,3, new Listener<WorkerInformationBean>() {

                    @Override
                    public void onStart(Object... params) {
                        showProgressDialog("请稍后...");
                    }

                    @Override
                    public void onComplete(WorkerInformationBean result, Object... params) {
                        dismissProgressDialog();
                        show("修改手机号码成功");
                        MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_MOBILE, str);
                        // tv_name.setText(name);
                        tv_phone.setText(str);
                    }

                    @Override
                    public void onFail(final String msg, Object... params) {
                        dismissProgressDialog();
                        if (TextUtils.isEmpty(msg)) {
                        } else {
                            show(msg);
                        }
                    }
                });

            }
            if (requestCode ==MODIFY_SPECIALITY) {
                final String str = data.getStringExtra("text");
                BusinessController.getInstance().modifyUserInformation(user_id, str,5, new Listener<WorkerInformationBean>() {

                    @Override
                    public void onStart(Object... params) {
                        showProgressDialog("请稍后...");
                    }

                    @Override
                    public void onComplete(WorkerInformationBean result, Object... params) {
                        dismissProgressDialog();
                        show("修改特长成功");
                        MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_SPECIALITY, str);
                        // tv_name.setText(name);
                        tv_speciality.setText(str);
                    }

                    @Override
                    public void onFail(final String msg, Object... params) {
                        dismissProgressDialog();
                        if (TextUtils.isEmpty(msg)) {
                        } else {
                            show(msg);
                        }
                    }
                });

            }
        }
    }

  /*  private Bitmap decodeUriAsBitmap(Uri uri){
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }*/

    //设置为男性
    public void changeSexToMale(View view) {
        //dialogUtils.dismiss();
        //tv_sex.setText("男");
       // MyApplication.local.saveOrUpdate("user_sex","男");
        upLoad("1");
    }
    //设置为女性
    public void changeSexToFemale(View view) {

        //tv_sex.setText("女");
      // MyApplication.local.saveOrUpdate("user_sex","女");
        upLoad("2");

    }

    void upLoad(final String sexFlag)
    {
        BusinessController.getInstance().modifyUserInformation(user_id,sexFlag,2, new Listener<WorkerInformationBean>() {

            @Override
            public void onStart(Object... params) {
                showProgressDialog("请稍后...");
            }

            @Override
            public void onComplete(WorkerInformationBean result, Object... params) {
                dismissProgressDialog();
                show("修改性别成功");
                // isUpdateHead=true;
                //MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.USER_HEAD_PATH, des.getAbsolutePath());
                String sexStr;
                if(sexFlag.equals("1"))
                    sexStr="男";
                else
                    sexStr="女";

                MyApplication.local.saveOrUpdate(user_id + LocalPreferencesHelper.USER_SEX,sexStr);
                //MyApplication.local.saveOrUpdate(user_id+LocalPreferencesHelper.USER_HEAD_CODE,result.random_code);
                //Bitmap bitmap=CropImageUtils.decodeUriAsBitmap(PersonInfoActivity.this,desUri);
                //img_head_view.setImageBitmap(bitmap);
                //  if(temp.exists())
                //      temp.delete();
                // if(des.exists())
                //     des.delete();

                dialogUtils.dismiss();
                tv_sex.setText(sexStr);

            }

            @Override
            public void onFail(final String msg, Object... params) {
                dismissProgressDialog();
                if (TextUtils.isEmpty(msg)) {
                } else {
                    show(msg);
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
          if(temp.exists())
              temp.delete();
         if(des.exists())
             des.delete();
    }
}
